<?php  
class AppController extends Controller { 
	var $helpers = array('Html', 'Javascript' );
	var $uses = array('User');
	var $components = array('cookie');
	
	function createRandomString($length = 10) {
	    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
	    srand((double)microtime()*1000000);
	    $i = 0;
	    $pass = '' ;
	    while ($i <= $length) {
	        $num = rand() % 33;
	        $tmp = substr($chars, $num, 1);
	        $pass = $pass . $tmp;
	        $i++;
	    }
	    return $pass;
	}
	
	function checkCookie() {
		if(!$this->Session->read('user')) {
			if($cookie = $this->cookie->read('login')) {
				
				$results = $this->User->findByCookie($cookie[1]); 
				if ($results && md5($results['User']['username']) == $cookie[0]) { 
					// Create a random string and save in in User and cookie
					$randomstring = $this->createRandomString(30);
					$results['User']['cookie'] = $randomstring;
					$value = array( md5($results['User']['username'] ), $randomstring);
					$this->cookie->write('login',$value,'+30 day');
					// Write session
					$this->Session->write('user', $results['User']['username']); 
					$this->Session->write('last_login', $results['User']['last_login']); 
					// Write last login
					$results['User']['last_login'] = date("Y-m-d H:i:s"); 
					$this->User->save($results); 
				}
			}
		}
	}
		
	function checkAccess() { 
		
		if (!$this->Session->valid()) { 
			$this->Session->renew(); 
		} 
		$this->checkCookie();
		if (!$this->Session->check('user')) { 
			$this->redirect("/users/login"); 
		} 
		if( $this->Session->read('user') != 'admin') { 
			$this->Session->setFlash('Berre innlogga brukare kan gjere admin ting.');
			$this->redirect("/users/login"); 
		} 
	}
	// Move to vendors..
	function calculatePages($model = null, $page = 1, $limit = 10, $condition = null ) {
	 	/*** Pagination ***/
		$pages = array();
		$j = 1;
		for($i=0; $i < $this->$model->findCount($condition); $i+=$limit) {
			$pages[] = $j;
			$j++;
		}
		if ($j != 2) {
			return $pages;
		} else {
			return false;
		}
	}
	function pre_admin () {
		$this->checkAccess();
		$this->layout = 'admin';
	}
} 

?>